const express = require('express');
const proxy = require('express-http-proxy');
var bodyParser = require("body-parser");
var querystring = require('querystring');
const path = require('path');
const { port=8060, proxy:proxyConfig={} } = require('./serverConfig');
 
const app = express();
 
app.use('/', express.static(path.join(__dirname, 'dist')))

app.use(bodyParser.json());  //body-parser 解析json格式数据

app.use(bodyParser.urlencoded({  //此项必须在 bodyParser.json 下面,为参数编码
  extended: true
}));

Object.keys(proxyConfig).map(key=>{
    app.use(key, proxy(proxyConfig[key].target, {
      proxyReqPathResolver: function(req, res) {
        console.log(req.body)
        // req.body = JSON.parse(req.body);
        // console.log(req.body)
        req.body = querystring.stringify(req.body)
        console.log(req.body)
        // console.log(proxyConfig[key].target+proxyConfig[key].pathRewrite[key]+require('url').parse(req.url).path)
        return proxyConfig[key].pathRewrite[key]+require('url').parse(req.url).path;
      },
      // proxyReqOptDecorator: function(req, res) {
      //   // req.headers['Referer'] = proxyConfig[key].target;
      //   // console.log(req)
      //   // console.log(res)
      //   var bodyContent = req.body
      //   // bodyContent=JSON.parse(bodyContent);
      //   // bodyContent=querystring.stringify(bodyContent);
      //   console.log(bodyContent)
      //   // req.headers['Body-Content'] = bodyContent
      //   req.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      // },
      // userResDecorator: function(proxyRes, proxyResData, userReq, userRes) {
      //   console.log(roxyRes, proxyResData, userReq, userRes)
      //   // data = JSON.parse(proxyResData.toString('utf8'));
      //   // data.newProperty = 'exciting data';
      //   return JSON.stringify(data);
      // }
      // proxyReqBodyDecorator : function(proxyReq,originalReq){
      //     // console.log(originalReq);
      //     console.log(proxyReq)
      //     proxyReq.body = originalReq.body;
      //     return proxyReq;
      // }
    }));
})

 
app.listen(port, ()=>{
    console.log(`server is running on port http://localhost:${port}`);
})